﻿using System;
using UnityEngine;

public class CityHudPart : MonoBehaviour
{
    [SerializeField] private Transform[] dividePart;

    private Vector3[] divedePartLocalPos;

    private Vector3 initScale;
    
    public void SetDivideBase(Transform t)
    {
        for (var i = 0; i < this.dividePart.Length; i++)
            if (this.dividePart[i].gameObject.activeInHierarchy)
                this.dividePart[i].SetParent(t);
    }

    public void OnPosChanged()
    {
        var curScale = transform.localScale;
        var xRatio = curScale.x / this.initScale.x;
        var yRatio = curScale.y / this.initScale.y;
        var zRatio = curScale.z / this.initScale.z;
        var pos = transform.position;
        for (var i = 0; i < this.dividePart.Length; i++)
        {
            var p = this.divedePartLocalPos[i];
            p.x *= xRatio;
            p.y *= yRatio;
            p.z *= zRatio;
            this.dividePart[i].position = pos + p;
        }
    }

    private void Awake()
    {
        this.initScale = transform.localScale;
        this.divedePartLocalPos = new Vector3[this.dividePart.Length];
        var pos = transform.position;
        for (var i = 0; i < this.dividePart.Length; i++)
            this.divedePartLocalPos[i] = this.dividePart[i].position - pos;
    }

    private void OnEnable()
    {
        for (var i = 0; i < this.dividePart.Length; i++)
            this.dividePart[i].SetActive(true);
    }

    private void OnDisable()
    {
        for (var i = 0; i < this.dividePart.Length; i++)
            this.dividePart[i].SetActive(false);
    }
    
    private void OnDestroy()
    {
        for (var i = 0; i < this.dividePart.Length; i++)
        {
            Destroy(this.dividePart[i].gameObject);
            this.dividePart[i] = null;
        }
    }
}
